package sg.edu.nus.comp.qa.database;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sg.edu.nus.comp.qa.question.ComparableQuestion;
import sg.edu.nus.comp.qa.question.parser.QuestionListParser;

public class QAMapGenerator {
	private static Log LOGGER = LogFactory.getLog(QAMapGenerator.class);
	private List<ComparableQuestion> questionList;
	private Map<String, List<Integer>> questionMap;
	private String outputfile;
	private QuestionListParser parser;
	
	public QAMapGenerator(String inputfile, String outputfile) throws FileNotFoundException{
		this.outputfile = outputfile;
		questionList = new ArrayList<ComparableQuestion>();
		questionMap = new HashMap<String, List<Integer>>();
		parser = new QuestionListParser();
		parser.loadFile(inputfile, questionList);
	}
	
	public void sort(){
		for(int i = 0; i < questionList.size(); i++){
			String[] words = questionList.get(i).getQuestion().split("[^a-zA-Z\\d:]");
			for(String word: words){
				if(questionMap.containsKey(word)){
					questionMap.get(word).add(i);
				} else{
					List<Integer> list = new ArrayList<Integer>();
					list.add(i);
					questionMap.put(word, list);
				}
			}
		}
	}
	
	public void writeFile(){
		try {
			Iterator<Entry<String, List<Integer>>> itr = questionMap.entrySet().iterator();
			while(itr.hasNext()){
				Entry<String, List<Integer>> entry = itr.next();
				String word = entry.getKey();
				List<Integer> list = entry.getValue();
				FileWriter writer = new FileWriter(new File(outputfile), true);
				writer.write(word + "	" + list.size() + "\n");
				for(int i : list){
					writer.write(i + " ");
				}
				writer.write('\n');
				writer.close();
			}
		} catch (IOException e) {
			LOGGER.error("IO Exception", e);
		}
	}
	
	public static void main(String[] args){
		if(args.length<2){
			LOGGER.error("Too few args, need to enter input filename and output filename");
			return;
		}
		try {
			QAMapGenerator generator = new QAMapGenerator(args[0], args[1]);
			generator.sort();
			generator.writeFile();
		} catch (FileNotFoundException e) {
			LOGGER.error("Error", e);
		}
		
	}
}
